package org.valire.db;

import java.io.File;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import dnl.toolbox.lang.ClassPathHacker;

/**
 * 
 * @author Daniel Orr
 * 
 */
public class DataSourceFactory {

	private static Logger logger = LoggerFactory
			.getLogger(DataSourceFactory.class);

	/**
	 * Creates a <code>DataSource</code> from the given connection info and
	 * driver path.
	 * 
	 * @param connectionInfo
	 * @param driverPath
	 * @return
	 * @throws Exception
	 */
	public static DataSource createDataSource(JdbcConnectionInfo connectionInfo
			) throws Exception {
		if(connectionInfo.getDriverPath() != null){
			File driverJar = new File(connectionInfo.getDriverPath());
			if (!driverJar.exists()) {
				logger
				.error("Could not locate jar: "
						+ driverJar.getAbsolutePath());
				System.exit(1);
			}
			ClassPathHacker.addFile(driverJar);
			// Class.forName(ci.getDriver());
		}

		BasicDataSource basicDs = new BasicDataSource();
		basicDs.setDriverClassName(connectionInfo.getDriver());
		basicDs.setUrl(connectionInfo.getJdbcUrl());
		basicDs.setUsername(connectionInfo.getUser());
		basicDs.setPassword(connectionInfo.getPassword());

		return basicDs;
	}
}
